const express = require('express');
const pool = require('./db'); // 引入数据库连接池
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

// 获取数据的 API (SELECT请求)
app.get('/api/data/shop/:uid', async (req, res) => {
  const uid = req.params.uid;
  try {
    const [rows] = await pool.query(
      'SELECT * FROM shop WHERE uid = ?',
      [uid]
    );
    if (rows.length === 0) {
      return res.status(404).json({ error: "数据不存在" });
    }
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 插入数据的 API (INSERT 请求)
app.post('/api/data', async (req, res) => {
  const { id, name, recommend } = req.body;
  try {
    console.log(req.body)
    const [result] = await pool.query(
      'INSERT INTO shop (id, name, recommend) VALUES (?, ?, ?)',
      [id, name, recommend]
    );
    res.json({ id: result.insertId });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 删除数据的 API (DELETE 请求)
app.delete('/api/data/:id', async (req, res) => {
  const id = req.params.id;
  try {
    const [result] = await pool.query(
      'DELETE FROM shop WHERE id = ?',
      [id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: "未找到对应数据" });
    }
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 获取单条数据的 API (SELECT请求)
app.get('/api/data/:id', async (req, res) => {
  const id = req.params.id;
  try {
    const [rows] = await pool.query(
      'SELECT * FROM shop WHERE id = ?',
      [id]
    );
    if (rows.length === 0) {
      return res.status(404).json({ error: "数据不存在" });
    }
    res.json(rows[0]);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// 更新数据的 API (PUT 请求)
app.put('/api/data/:id', async (req, res) => {
  const id = req.params.id;
  const { recommend } = req.body;
  
  try {
    const [result] = await pool.query(
      'UPDATE shop SET recommend = ? WHERE id = ?',
      [ recommend, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ error: "未找到对应数据" });
    }
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});


const PORT = 3001;
app.listen(PORT, () => {
  console.log(`后端服务运行在 http://localhost:${PORT}`);
});